<?php

namespace app\admin\controller\shopro;

use addons\shopro\service\Wallet as WalletService;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;

/**
 * 进货列管理
 *
 * @icon fa fa-circle-o
 */
class Shoprestock extends Backend
{

    /**
     * Shoprestock模型对象
     * @var \app\admin\model\shopro\Shoprestock
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\Shoprestock;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['shop','goods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','goods_id','goods_num','status','remark','createtime','updatetime','all_money']);
                $row->visible(['shop']);
				$row->getRelation('shop')->visible(['shop_name','logo']);
				$row->visible(['goods']);
				$row->getRelation('goods')->visible(['subtitle','image','price']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 批量发货
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $bili  = config('site.shop_recommended')/100;
            $shopModel = new \app\admin\model\shopro\Shop();
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->where('status','=',0)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                if($item->type == 1){
                    $shop_info = $shopModel->where(['id'=>$item['shop_id'],'parent_id'=>['neq',0]])->find();
                    if($shop_info){
                        $amount = bcmul($item['all_money'], $bili);
                        WalletService::change($shop_info['parent_id'], 'golden', $amount, 'shop_restock', [],
                            $shop_info['shop_name'].'进货推荐奖');
                    }
                }

            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
}
